#!/bin/bash

# 设置颜色和样式
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# 进度条函数
show_progress() {
    local width=50  # 固定宽度为50个字符
    local progress=0
    
    echo -n "["
    for ((i=0; i<width; i++)); do
        echo -n " "
    done
    echo -n "] 0%"
    
    for ((i=0; i<=width; i++)); do
        progress=$((i * 100 / width))
        echo -ne "\r["
        for ((j=0; j<i; j++)); do
            echo -n "▓"
        done
        for ((j=i; j<width; j++)); do
            echo -n " "
        done
        echo -n "] $progress%"
        sleep 0.1
    done
    echo
}

# 显示欢迎界面
clear
echo -e "${CYAN}${BOLD}"
cat << "EOF"
██╗    ██╗███████╗ ██████╗██╗  ██╗ █████╗ ████████╗
██║    ██║██╔════╝██╔════╝██║  ██║██╔══██╗╚══██╔══╝
██║ █╗ ██║█████╗  ██║     ███████║███████║   ██║   
██║███╗██║██╔══╝  ██║     ██╔══██║██╔══██║   ██║   
╚███╔███╔╝███████╗╚██████╗██║  ██║██║  ██║   ██║   
 ╚══╝╚══╝ ╚══════╝ ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   
EOF
echo -e "${NC}"
echo -e "${BLUE}${BOLD}微信机器人部署系统 - 高级安装向导${NC}\n"

echo -e "${CYAN}[1/4]${NC} 系统初始化检查..."
show_progress 100

# 检查并创建必要的目录
echo -e "\n${CYAN}[2/4]${NC} 创建必要目录..."
mkdir -p /root/WeChatPadPro
show_progress 50

# 克隆WeChatPadPro仓库
echo -e "\n${CYAN}[3/4]${NC} 克隆 WeChatPadPro 仓库..."
cd /root
git clone https://gh.llkk.cc/https://github.com/bclz-wyz/WeChatPadPro-Docker --depth 1
show_progress 100

# 启动容器
echo -e "\n${CYAN}[4/4]${NC} 启动 WeChatPadPro 容器..."
cd /root/WeChatPadPro-Docker
docker compose up -d

# 设置开机自启
docker update --restart=always wechatpadpro

# 获取本地IP
LOCAL_IP=$(ip addr show | grep -w inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1)

# 如果本地IP以17开头，直接使用
if echo "$LOCAL_IP" | grep -q "^17"; then
    SERVER_IP=$LOCAL_IP
else
    # 否则获取本地IP的第三段
    LOCAL_IP=$(echo "$LOCAL_IP" | grep ^192)
    SUBNET=$(echo "$LOCAL_IP" | cut -d. -f3)
    # 查找对应的 17X.${SUBNET} 开头的IP
    SERVER_IP=$(ifconfig | grep -B1 "inet 17" | grep inet | awk '{print $2}' | grep "^17.*\.${SUBNET}\.")
fi

# 显示完成界面
clear
echo -e "${GREEN}${BOLD}"
cat << "EOF"
✨ 部署完成！WeChatPadPro 已成功启动 ✨
EOF
echo -e "${NC}"

echo -e "${CYAN}==================================${NC}"
echo -e "${BOLD}WeChatPadPro 管理面板：${NC}"
echo -e "${BLUE}▶ http://${SERVER_IP}:8849${NC}"
echo -e "${CYAN}==================================${NC}"

echo -e "\n${GREEN}服务状态：${NC}"
docker ps | grep wechatpadpro

echo -e "\n${YELLOW}提示：${NC}"
echo -e "1. 如需查看日志，请使用命令：${BOLD}docker logs -f wechatpadpro${NC}"
echo -e "2. 如需停止服务，请使用命令：${BOLD}docker stop wechatpadpro${NC}"
echo -e "3. 如需重启服务，请使用命令：${BOLD}docker restart wechatpadpro${NC}"
echo -e "4. 请注意：${BOLD}需要手动扫码登录，且需要有一台手机在线${NC}"

exit 0 